package com.android.flowoflife.activities;

import com.android.flowoflife.adapters.ProfileDbAdapter;
import com.android.flowoflife.R;

import android.app.Activity;
import android.app.Dialog;
import android.app.DatePickerDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import java.util.Calendar;

public class EditProfile extends Activity {

	private EditText mTitleText;
	private EditText mFreqText;
    private EditText mStartDateText;
    private EditText mEndDateText;
    private Long mRowId;
    private ProfileDbAdapter mDbHelper;

    private Button mPickStartDate;
    private Button mPickEndDate;

    private int mYear;
    private int mMonth;
    private int mDay;

    // the callback received when the user "sets" the date in the dialog
    private DatePickerDialog.OnDateSetListener mDateSetListenerS =
        new DatePickerDialog.OnDateSetListener() {
			@Override
            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateStartDateDisplay();
            }
        };
    private DatePickerDialog.OnDateSetListener mDateSetListenerE =
            new DatePickerDialog.OnDateSetListener() {
    			@Override
                public void onDateSet(DatePicker view, int year, 
                                      int monthOfYear, int dayOfMonth) {
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateEndDateDisplay();
                }
            };

    static final int SDATE_DIALOG_ID = 0;
    static final int EDATE_DIALOG_ID = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDbHelper = new ProfileDbAdapter(this);
        mDbHelper.open();
        setContentView(R.layout.profiler_flow);
        
       
        mTitleText = (EditText) findViewById(R.id.title);
        mFreqText = (EditText) findViewById(R.id.frequency);
        mStartDateText = (EditText) findViewById(R.id.start_date);
        mEndDateText = (EditText) findViewById(R.id.end_date);
      
        Button confirmButton = (Button) findViewById(R.id.confirm);

        mPickStartDate = (Button) findViewById(R.id.get_start_date);
        mPickEndDate = (Button) findViewById(R.id.get_end_date);

        // add a click listener to the button
        mPickStartDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(SDATE_DIALOG_ID);
            }
        });
        mPickEndDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(EDATE_DIALOG_ID);
            }
        });

        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        mRowId = savedInstanceState != null ? savedInstanceState.getLong(ProfileDbAdapter.KEY_ROWID) 
                							: null;
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();            
			mRowId = extras != null ? extras.getLong(ProfileDbAdapter.KEY_ROWID) 
									: null;
		}

		populateFields();
		
        confirmButton.setOnClickListener(new View.OnClickListener() {

        	public void onClick(View view) {
        	    setResult(RESULT_OK);
        	    finish();
        	}
          
        });
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case SDATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListenerS,
                        mYear, mMonth, mDay);
        case EDATE_DIALOG_ID:
            return new DatePickerDialog(this,
                        mDateSetListenerE,
                        mYear, mMonth, mDay);
        }
        return null;
    }

    // updates the date we display in the TextView
    private void updateStartDateDisplay() {
        mStartDateText.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }

    private void updateEndDateDisplay() {
        mEndDateText.setText(
            new StringBuilder()
                    // Month is 0 based so add 1
                    .append(mMonth + 1).append("-")
                    .append(mDay).append("-")
                    .append(mYear).append(" "));
    }

    private void populateFields() {
        if (mRowId != null) {
            Cursor profile = mDbHelper.fetchProfile(mRowId);
            startManagingCursor(profile);
            mTitleText.setText(profile.getString(
    	            profile.getColumnIndexOrThrow(ProfileDbAdapter.KEY_TITLE)));
            mFreqText.setText(profile.getString(
    	            profile.getColumnIndexOrThrow(ProfileDbAdapter.KEY_FREQ)));
            mStartDateText.setText(profile.getString(
                    profile.getColumnIndexOrThrow(ProfileDbAdapter.KEY_START_DATE)));
            mEndDateText.setText(profile.getString(
                    profile.getColumnIndexOrThrow(ProfileDbAdapter.KEY_END_DATE)));
        }
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(ProfileDbAdapter.KEY_ROWID, mRowId);
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        saveState();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        populateFields();
    }
    
    private void saveState() {
        String title = mTitleText.getText().toString();
        String frequency = mFreqText.getText().toString();
        String start_date = mStartDateText.getText().toString();
        String end_date = mEndDateText.getText().toString();

        if (mRowId == null) {
            long id = mDbHelper.createProfile(title, frequency, start_date, end_date);
            if (id > 0) {
                mRowId = id;
            }
        } else {
            mDbHelper.updateProfile(mRowId, title, frequency, start_date, end_date);
        }
    }
}
